export default {
  namespaced: true,
  state: {
    num: 1,
    cartList: []
  },
  mutations: {
    setNum(state, value) {
      state.num = value
    },
    setCartList(state, obj) {
      const findItem = state.cartList.find(item => item.goods_id === obj.goods_id)
      if (findItem) {
        // 存在：只需要在以前商品基础上数量+1
        findItem.goods_count++
      } else {
        // 不存在：正常添加到前面
        state.cartList.unshift(obj)
      }
    },
    // 修改购物车某一项的选中状态
    setStatus(state, goods_id) {
      const findItem = state.cartList.find(item => item.goods_id === goods_id)
      if (findItem) {
        findItem.goods_status = !findItem.goods_status
      }
    },
    // 修改数量  obj={goods_id,goods_count}
    setCount(state, obj) {
      const findItem = state.cartList.find(item => item.goods_id === obj.goods_id)
      if (findItem) {
        findItem.goods_count = obj.goods_count
      }
    },
    // 删除
    delList(state, goods_id) {
      // [{id:1},{id:2},{id:3}]
      // filter过滤:删除id=2 ===== 把id!=2过滤出来赋值到新的数组
      state.cartList = state.cartList.filter(item => item.goods_id !== goods_id)
    },
    // 修改选中状态
    setListStatus(state, bool) {
      state.cartList.forEach(item => item.goods_status = bool)
    },
    // 清理已支付数据
    clearPayList(state) {
      state.cartList = state.cartList.filter(item => !item.goods_status)
    }
  },
  actions: {},
  getters: {
    // 全选： true:所有项都选中  false:只要有一个项不选中
    isAll(state) {
      // every:所有项都满足条件  some:只要一个项满足条件
      return state.cartList.every(item => {
        return item.goods_status
      })
    },
    // 商品总价:商品中已勾选商品的价格*数量总合
    totalPrice(state) {
      return state.cartList.reduce((prv, item) => {
        if (item.goods_status) {
          return prv + item.goods_count * item.goods_price
        } else {
          return prv
        }
      }, 0)
    },
    // 购物车内已勾选商品总和
    total(state) {
      return state.cartList.reduce((prev, item) => {
        // 已勾选
        if (item.goods_status) {
          return prev + item.goods_count
        } else {
          return prev
        }
      }, 0)
    }
  }
}